package com.example.yichuangyun.service;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.model.PushModel;
import com.example.yichuangyun.ui.activity.MainActivity;
import com.example.yichuangyun.utils.SystemUtil;
import com.example.yichuangyun.utils.sharedpreference.SPUtil;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTTransmitMessage;

import org.greenrobot.eventbus.EventBus;

/**
 * 继承 GTIntentService 接收来自个推的消息，所有消息在主线程中回调，如果注册了该服务，则务必要在 AndroidManifest 中声明，否则无法接受消息
 */
public class GeTuiIntentService extends GTIntentService {

    @Override
    public void onReceiveServicePid(Context context, int pid) {
    }

    /**
     * 处理透传消息
     */
    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        // 透传消息的处理，详看 SDK demo
        try {
            byte[] payload = msg.getPayload();
            try {
                if (payload != null) {
                    String message = new String(payload);
                    PushModel pushModel = JSON.parseObject(message, PushModel.class);
                    Constant.pushBusinessId = pushModel.getServiceId();
                    Constant.pushServiceType = pushModel.getServiceType();
                    Log.e("@@@@@@@", message);
                    SystemUtil.wakeUpAndUnlock();
                    if (!MyApplication.isForeground) {
                        ToMain();
                        SystemUtil.setTopApp(context);
                    }
                    EventBus.getDefault().post(pushModel);
                }
            } catch (Exception e) {
                Log.e(TAG, "onReceiveMessageData: e: ", e);
            }
        } catch (Exception e) {
            Log.e(TAG, "onReceiveMessageData: e: ", e);
        }
    }

    /**
     * 接收clientId
     */
    @Override
    public void onReceiveClientId(Context context, String clientId) {
        Log.e("GeTuiIntentService", "clientId = " + clientId);
        SPUtil.put(Constant.clientIdKey, clientId);
    }

    private void ToMain() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
